<?php
    class UserControl extends Control {
        public static $keyDesc = array(
            "email"     => "Email",
            "password"  => "Password"
        );
        
        protected static $_callable = array(
            "createUser",
            "deleteUserWeight",
            "getUserWeight",
            "load",
            "save"
        );
        
        protected static $_noLogin = array(
            "createUser"    
        );
        
        /**
         * Funktio luo uuden käyttäjän tietokantaan.
         *
         * @return  string
         */
        public static function createUser($data) {
            DB::begin();
            
            try {
                $user = new UserModel();
                
                $user->email        = $data;
                $user->firstname    = $data;
                $user->lastname     = $data;
                $user->timezoneid   = $data;
                $user->default_unit = $data;
                $user->timeout_min  = $data;
                
                # Salasana
                $password = arrGet($data,"password");                
                $password2 = arrGet($data,"password2");
                if ($password || $password2) {
                    $user->setPassword($password,$password2);
                }
                
                $user->write();                
                $hashid = $user->hashid;
            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }
            
            DB::commit();
            
            return $hashid;    
        }
        
        /**
         * Funktio poistaa käyttäjän painotiedon tietokannasta.
         *
         * @return bool
         */
        public static function deleteUserWeight($data) {
            $result = false;
            
            DB::begin();
            
            try {
                $weight = new UserWeightModel(array(
                    "hashid" => arrGet($data,"hashid")
                ));
                
                # Tarkasta onko painotieto liitetty harjoitukseen
                $query = DB::preparedQuery("
                    SELECT id
                    FROM workout
                    WHERE user_weightid=:id
                    LIMIT 1
                ",array(
                    "id" => $weight->id
                ));
                if (DB::numRows($query) == 1) {
                    DB::freeResult($query);
                    throw new DBException(
                        "User weight data is attached to one or more workouts",
                        40,
                        __CLASS__,
                        "User weight data is attached to one or more workouts"
                    );
                }
                
                $weight->delete();
                
                $result = true;
            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }
            
            DB::commit();
            
            return $result; 
        }
        
        /**
         * Funktio hakee käyttäjän painotiedot tietokannasta.
         *
         * @param   array   $data   Hakuparametrit
         * @return  array
         */
        public static function getUserWeight($data) {
            $result = array(                
                "list"          => array(),
                "totalCount"    => 0
            );
            
            $params = array(
                "userid" => LoginControl::get("userid")
            );
            $where = "";
            
            # Hashid
            if (isset($data["hashid"]) && $data["hashid"]) {
                $params["hashid"] = $data["hashid"];
                $where .= " AND user_weight.hashid=:hashid";
            }
            
            # Alkupvm
            if (isset($data["startdate"]) && $data["startdate"]) {
                $d = DateTime::createFromFormat("Y-m-d",$data["startdate"]);
                if ($d) {
                    $params["startdate"] = $d->format("Y-m-d");
                    $where .= " AND user_weight.date>=:startdate";
                }
            }
            
            # Loppupvm
            if (isset($data["enddate"]) && $data["enddate"]) {
                $d = DateTime::createFromFormat("Y-m-d",$data["enddate"]);
                if ($d) {
                    $params["enddate"] = $d->format("Y-m-d");
                    $where .= " AND user_weight.date<=:enddate";
                }
            }
            
            # Suorita haku
            $query = DB::preparedQuery("
                SELECT hashid,
                  weight_kg,
                  weight_lb,
                  unit,
                  measurement_time,
                  fatpercent,
                  date,
                  updated,
                  rowstamp
                FROM user_weight
                WHERE userid=:userid{$where}
                ORDER BY date DESC,measurement_time DESC,id
                LIMIT 10000
            ",$params);
            $numrows = DB::numRows($query);
            if ($numrows > 0) {
                while ($row = DB::fetchAssoc($query)) {
                    $result["list"][] = $row;
                }
                DB::freeResult($query);
                
                $result["totalCount"] = $numrows;
            }
            
            return $result;
        }
        
        /**
         * Funktio hakee kirjautuneen käyttäjän tiedot tietokannasta.
         *
         * @return  array
         */
        public static function load() {
            $result = array();
            
            $user = LoginControl::get("userdata");
            
            $result["hashid"]       = $user->hashid;
            $result["email"]        = $user->email;
            $result["firstname"]    = $user->firstname;
            $result["lastname"]     = $user->lastname;
            $result["timezoneid"]   = $user->timezoneid;
            $result["default_unit"] = $user->default_unit;
            $result["timeout_min"]  = $user->timeout_min;
            $result["updated"]      = $user->updated;
            $result["rowstamp"]     = $user->rowstamp;

            return $result;
        }
        
        /**
         * Funktio päivittää käyttäjän tiedot tietokantaan.
         *
         * @return  string
         */
        public static function save($data) {
            DB::begin();
            
            try {
                $userid = LoginControl::get("userid");
                $user = new UserModel($userid);
                
                $user->email        = $data;
                $user->firstname    = $data;
                $user->lastname     = $data;
                $user->timezoneid   = $data;
                $user->default_unit = $data;
                $user->timeout_min  = $data;
                $user->updated      = date("Y-m-d H:i:s");
                
                # Salasana
                $password = arrGet($data,"password");                
                $password2 = arrGet($data,"password2");
                if ($password || $password2) {
                    $user->setPassword($password,$password2);
                }
                
                $user->write();                
                $hashid = $user->hashid;
            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }
            
            DB::commit();
            
            return $hashid;
        }
    }